package com.woniuxy.mapper.impl;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 作者
 * @create 2025-06-16 16:48
 */
public class JdbcUtil {

    public static Connection getConnection() throws Exception {
        String className = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql:///db1";
        String user = "root";
        String password = "123";
        Class.forName(className);
        return DriverManager.getConnection(url, user, password);
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    //"??????"
    public static int executeUpdate(Connection connection, String sql, Object... obj) throws Exception {

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (obj != null && obj.length > 0) {
            for (int i = 0; i < obj.length; i++) {
                preparedStatement.setObject(i + 1, obj[i]);
            }
        }
        int num = preparedStatement.executeUpdate();
        close(connection, preparedStatement, null);
        return num;

    }
    public static <T> List<T> executeQuery(Connection connection, Class<T> clazz, String sql, Object... obj) throws Exception {
        T entity=null;
        List<T> list=new ArrayList<>();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (obj != null && obj.length > 0) {
            for (int i = 0; i < obj.length; i++) {
                preparedStatement.setObject(i + 1, obj[i]);
            }
        }
        //查询数据，转成对象的集合
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        while(resultSet.next()){
            //读取一条数据,创建对象,
            entity=clazz.newInstance();
            //使用反射给属性赋值
            for(int i=0;i<metaData.getColumnCount();i++){
                //获取列名
                String columnName = metaData.getColumnName(i+1);
                //根据列名找对应的Filed
                Field field = clazz.getDeclaredField(columnName);
                field.setAccessible(true);
                //给当前对象的属性赋值
                field.set(entity,resultSet.getObject(i+1));
            }
            list.add(entity);
        }
        close(connection, preparedStatement, null);
        return list;

    }


    public static <T> T executeQueryOne(Connection connection, Class<T> clazz, String sql, Object... obj) throws Exception {
        List<T> list = executeQuery(connection, clazz, sql, obj);
        if(list.size()>0){
            return list.get(0);
        }
        return null;

    }


}
